package org.darcy.controller.admin.site;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.darcy.entity.BizFile;
import org.darcy.framework.annotation.BussinessLog;
import org.darcy.framework.model.PageParam;
import org.darcy.framework.model.ResponseVO;
import org.darcy.framework.util.ResultUtil;
import org.darcy.model.BizFileModel;
import org.darcy.service.BizFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.util.StrUtil;

/**
 * 文件管理
 */
@RestController
@RequestMapping("/file")
public class FileController {

	@Autowired
	private BizFileService fileService;

	@RequiresPermissions("files")
	@PostMapping("/list")
	public Map list(BizFileModel param) {
		Page p = new Page(param.getP(), param.getPageSize());
		QueryWrapper<BizFile> q = new QueryWrapper<BizFile>();
		if (StrUtil.isNotEmpty(param.getOriginalFileName()))
			q.like("original_file_name", param.getOriginalFileName());
		q.orderByDesc("upload_start_time");
		IPage pageInfo = fileService.getPage(p, q);
		Map m = new HashMap();
		m.put("list", pageInfo.getRecords());
		m.put("pageParam", PageParam.getParam((Page)pageInfo));
		return m;
	}

	@RequiresPermissions("files")
	@PostMapping(value = "/remove")
	@BussinessLog("删除文件，ids:{1}")
	public ResponseVO remove(Long[] ids) {
		if (null == ids) {
			return ResultUtil.error(500, "请至少选择一条记录");
		}
		fileService.remove(ids);
		return ResultUtil.success("成功删除 [" + ids.length + "] 张图片");
	}

	@RequiresPermissions("files")
	@PostMapping(value = "/add")
	@BussinessLog("添加文件")
	public ResponseVO add(MultipartFile[] file) {
		if (null == file || file.length == 0) {
			return ResultUtil.error("请至少选择一张图片！");
		}
		int res = fileService.upload(file);
		return ResultUtil.success("成功上传" + res + "张图片");
	}
}
